<template>
  <el-select
    v-model="selectVal"
    :placeholder="placeholder"
    :loading="loading"
    :multiple="multiple"
    :filterable="filterable"
    :clearable="clearable"
    :disabled="disabled"
    :collapse-tags="multiple && !disabled"
    @change="handleSelectChange"
  >
    <el-option label='全选' value='全选' @click.native='handleSelectAll'></el-option>
    <el-option
      v-for="(item, key) in list"
      :key="key"
      :label="item.addressName"
      :value="item.addressCode">
    </el-option>
  </el-select>
</template>

<script>
import { queryAddressListService } from '@api/supplier/components';

export default {
  name: 'ProvinceSelect',
  props: {
    value: [String, Number, Array],
    placeholder: { type: String, default: '请选择省份' },
    multiple: { type: Boolean, default: false },
    filterable: { type: Boolean, default: false },
    clearable: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
  },
  data () {
    return {
      loading: false,
      selectVal: this.multiple ? [] : '',
      list: []
    }
  },
  watch: {
    value: {
      handler (val) {
        if (val) {
          this.selectVal = val;
        }
      },
      immediate: true,
    },
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      this.loading = true
      const resp = await queryAddressListService({ addressLevel: 101 })
      if (resp && resp.status === '0' && resp.result) {
        this.list = resp.result
      } else {
        this.list = []
      }
      this.loading = false
    },
    handleChange (value) {
      // 值回显父组件
      this.$emit('input', this.selectVal);
      // change事件
      this.$emit('change', this.selectVal);
      //
      if (this.multiple) {
        this.$emit('onSelected', this.list.filter(i => value.includes(i.addressCode)))
      } else {
        this.$emit('onSelected', this.list.find(item => item.addressCode === value))
      }
    },
    resetSelectVal () {
      this.selectVal = this.multiple ? [] : ''
    },
    handleSelectAll () {
      if (this.selectVal.length < this.list.length) {
        this.selectVal = this.list.map(item => item.addressCode)
        // this.selectVal.unshift('全选')
      } else {
        this.selectVal = []
      }
      this.handleChange(this.selectVal)
    },
    handleSelectChange (val) {
      if (!val.includes('全选') && val.length === this.list.length) {
        this.selectVal.unshift('全选')
      } else if (val.includes('全选') && (val.length - 1) < this.list.length) {
        this.selectVal = this.selectVal.filter(item => item !== '全选')
      }
      this.handleChange(val)
    },
    removeTag (val) {
      if (val === '全选') {
        this.selectVal = []
      }
    }
  }
}
</script>
